const db = require("../db");


exports.getUserInfo = (req, res) => {
    console.log(req.user.uname);
    res.send('okok')
}
exports.answer = (req, res) => {
    const sql = 'insert into homework set ?';
    const uname = req.user.uname;
    const main_title = req.body.main_title;
    console.log(main_title);
    const answer = JSON.stringify(req.body)
    console.log(req.user);
    const sqlStr = 'select answer from homework where uname = ? and title = ?'
    // const sqlStr = 'select answer from homework where title = ? and uanem = ?'
    db.query(sqlStr, { title : main_title, uname : uname }, function (err,resules) {
        if (err) return res.send({ status: 1, message: err.message })
        if (resules.length > 0) {
            const sql_update = "UPDATE answer SET answer = ? WHERE answer = ?"
            connection.query(sql_update, [answer,resules],function(err,result) {
                if(err){  
                    console.log('error');  
                    return;  
                }
                console.log(result);
            });
        } else {
            db.query(sql,{uname:uname,title:main_title,answer:answer}, function (err, results) {
                if (err) return res.send({ status: 1, message: err.message })
                if (results.affectedRows !== 1) { return res.send({ status: 1, message: '提交失败' }) }
                res.send({ status: 0, message: '添加成功！' })
            })
        }
    })







}
//检查  返回学生的名字列表
exports.inspect = (req, res) => {
    
    const sqlStr = 'select uname from user';
    db.query(sqlStr, (err, resules) => {
        if (err) {
            return res.send({ status: 1, message: err.message });
        }
        res.send(resules)
    })

}
exports.get_student_answer = (req, res) => {
    console.log(231);
    let data = Object.keys(req.body)
    // data = JSON.parse(data);
    // console.log(data);
    // data = JSON.parse(data+'')
    data = JSON.parse(data[0])
    const name = data.name
    const title = data.title
    // console.log(data);
    const sqlStr = 'select answer from homework where uname = ? and title = ?'
    db.query(sqlStr,[name,title],(err, resules) => {
        if (err) {
            return res.send({ status: 1, message: err.message });
        }
        // console.log(resules);
        res.send(resules)
    })

}